package StudyCode.summary.csv;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

/**
 * 版权所有 科技与人文(www.tah1986.com)
 */
public class CSVContentParser {
	private static final char DEFAULT_CSV_SEPARATOR = ';';

	public static List<List<String>> parseCsv(InputStream csvInput) {
		return parseCsv(csvInput, DEFAULT_CSV_SEPARATOR);
	}


	public static List<List<String>> parseCsv(InputStream csvInput,
	                                          char csvSeparator) {

		BufferedReader csvReader = null;
		List<List<String>> csvList = new ArrayList<List<String>>();
		String csvRecord = null;

		try {
			csvReader = new BufferedReader(new InputStreamReader(csvInput,
					"UTF-8"));
			while ((csvRecord = csvReader.readLine()) != null) {
				csvList.add(parseCsvRecord(csvRecord, csvSeparator));
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (csvReader != null)
				try {
					csvReader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
		}

		return csvList;
	}


	private static List<String> parseCsvRecord(String record,
	                                           char csvSeparator) {

		boolean quoted = false;
		StringBuilder fieldBuilder = new StringBuilder();
		List<String> fields = new ArrayList<String>();

		for (int i = 0; i < record.length(); i++) {
			char c = record.charAt(i);
			fieldBuilder.append(c);

			if (c == '"') {
				quoted = !quoted;
			}

			if ((!quoted && c == csvSeparator)
					|| i + 1 == record.length()) {
				String field = fieldBuilder.toString()
						.replaceAll(csvSeparator + "$", "")
						.replaceAll("^\"|\"$", "")
						.replace("\"\"", "\"");
				fields.add(field.trim());
				fieldBuilder = new StringBuilder();
			}
		}

		return fields;
	}
}
